package org.dataone.dataUsage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.dataone.client.D1RestClient;
import org.dataone.service.util.TypeMarshaller;

public class DocMetric {
	private String CN_URL;
	public String getCN_URL() {
		return CN_URL;
	}
	public void setCN_URL(String cN_URL) {
		CN_URL = cN_URL;
	}
	/**
	 * This method is to obtain Document metric data. Returns an ArrayList of
	 * MonthlyMetric type for a certain identifier
	 * 
	 * @param identifier
	 *            the identifier for a document
	 * @param timespan
	 *            the time span for data display
	 */
	public ArrayList<MonthlyMetric> getDocMetricsByMonth(String identifier,
			int timespan) {
		ArrayList<MonthlyMetric> result = new ArrayList<MonthlyMetric>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Calendar c1 = Calendar.getInstance();
		c1.add(Calendar.MONTH, -(timespan));
		for (int i = 0; i < timespan; i++) {
			String metricDate = sdf.format(c1.getTime());
			String starttime = sdf.format(c1.getTime()) + "-01T00:00:00.0000Z";
			c1.add(Calendar.MONTH, 1);
			String endtime = sdf.format(c1.getTime()) + "-01T00:00:00.0000Z";
			try {
				MonthlyMetric temp = new MonthlyMetric();
				temp.setMetricValue(getDocCNLog(identifier, starttime, endtime));
				temp.setMetricDate(metricDate);
				result.add(temp);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	/**
	 * This method is to get the exact document download number from CN server.
	 * 
	 * @param pid
	 *            the document identifier
	 * @param startDate
	 *            the data starts point
	 * @param endDate
	 *            the data ends point
	 */
	public String getDocCNLog(String pid, String startDate, String endDate) {
		D1RestClient CNclient = new D1RestClient();
		String url = CN_URL + "/cn/v1/log/?event=read&fromDate=" + startDate
				+ "&toDate=" + endDate + "&count=0&pidFilter=" + pid;
		try {
			org.dataone.service.types.v1.Log log = TypeMarshaller
					.unmarshalTypeFromStream(
							org.dataone.service.types.v1.Log.class,
							CNclient.doGetRequest(url, true));

			return Integer.toString(log.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
}
